﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LitTools
{
    /// <summary>
    /// 物体对象池元素
    /// </summary>
    public class GameObjectPoolItem : MonoBehaviour, IObjectPoolItem
    {
        /// <summary>
        /// 元素所在对象池
        /// </summary>
        public GameObjectPool pool;
        /// <summary>
        /// 当前存活时间
        /// </summary>
        private float lifeTime;

        #region 对象池接口
        public virtual void OnBeforeRent()
        {
            lifeTime = 0;
            gameObject.SetActive(true);
        }

        public virtual void OnBeforeReturn()
        {
            gameObject.SetActive(false);
        }

        public virtual void OnCreate()
        {
            gameObject.SetActive(true);
        }

        public virtual void OnRelease()
        {
            Destroy(gameObject);
        }
        #endregion

        #region 生命周期
        private void OnDisable()
        {
            if (pool != null
                && pool.returnWhenDisable)
                pool.ReturnObject(this);
        }
        private void Update()
        {
            if (pool.autoReturnTime > 0)
            {
                lifeTime += Time.deltaTime;
                if (lifeTime >= pool.autoReturnTime)
                {
                    pool.ReturnObject(this);
                }
            }
        }

        private void OnDestroy()
        {
            pool.ReleaseObject(this);
        }
        #endregion
    }
}
